import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Layout from '@/layout/index.vue'
import { usePermissionStore } from '@/stores/modules/permission'
import { loginApi, permissionApi } from '@/api'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { isLogin, isWhiteList } from './routeBefore'
import { LoginUser } from '@/api/login/type'
import { ElMessage } from 'element-plus'

NProgress.configure({ showSpinner: false })

export const constantRoutes: RouteRecordRaw[] = [
  {
    path: '/redirect',
    component: Layout,
    meta: { hidden: true },
    children: [
      {
        path: '/redirect/:path(.*)',
        component: () => import('@/views/redirect/index.vue')
      }
    ]
  },
  {
    path: '/',
    meta: { hidden: true },
    redirect: '/index'
  },
  {
    path: '',
    component: Layout,
    redirect: '/index',
    meta: {
      single: true
    },
    children: [
      {
        name: 'dashboard',
        path: '/index',
        component: () => import('@/views/dashboard/index.vue'),
        meta: { title: '首页', icon: 'dashboard', single: true, affix: true }
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue'),
    meta: {
      title: '登录',
      hidden: true
    }
  }
]

// 动态路由，基于用户权限动态去加载
export const dynamicRoutes: RouteRecordRaw[] = []

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: constantRoutes,
  // 刷新时，滚动条位置还原
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    }
    return { top: 0 }
  }
})

// 添加一个标记，用于跟踪动态路由是否已经加载
let isDynamicRoutesAdded = false

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (isWhiteList(to.path)) {
    next()
    NProgress.done()
  } else if (!isLogin()) {
    console.log('未登录')
    next('/login') // 否则全部重定向到登录页
    NProgress.done()
  } else if (isDynamicRoutesAdded) {
    console.log('已登录')
    next()
    NProgress.done()
  } else {
    const loginUser: LoginUser = JSON.parse(window.sessionStorage.getItem('loginUser')!)
    try {
      const menuList: any = await permissionApi.findSideMenuList(
        loginUser.userSysId,
        process.env.VITE_APP_SYSTEM_ID
      )
      const accessRoutes = usePermissionStore().generateRoutes(menuList)
      console.log('accessRoutes', accessRoutes)

      // 根据roles权限生成可访问的路由表
      accessRoutes.forEach((route) => {
        router.addRoute(route) // 动态添加可访问路由表
      })
      isDynamicRoutesAdded = true
      next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
      NProgress.done()
    } catch (err: any) {
      ElMessage.error('获取菜单失败:' + err)
      next('/login')
      NProgress.done()
    }
  }
})

export default router
